﻿using Abp.Timing;
using Hicap.QRCodeWarehouse.Processor.Model;
using System;
using System.Globalization;

namespace Hicap.QRCodeWarehouse.Processor.Helper
{
    public static class CodeHelper
    {
        private static double NextDouble(this Random random, double miniDouble, double maxiDouble)
        {
            if (random != null)
            {
                return random.NextDouble() * (maxiDouble - miniDouble) + miniDouble;
            }
            else
            {
                return 0.0d;
            }
        }

        private static int GetRandomSeedbyGuid()
        {
            return new Guid().GetHashCode();
        }

        public static QrCodeRecord[] GetIncreamentAndRandomCode(CodeGenConfig config, int taskId, string prefix)
        {
            long num = Convert.ToInt64(config.Num);
            QrCodeRecord[] result = new QrCodeRecord[num];
            Random random = new Random(GetRandomSeedbyGuid());
            for (int i = 0; i < config.Num; i++)
            {
                string randomStr = GetRandomString(config, random);
                result[i] = new QrCodeRecord()
                {
                    Code = prefix + randomStr +
                           (config.StartIncreament).ToString().PadLeft(config.IncreamentLength, '0'),
                    TaskId = taskId,
                    IsDownloaded = false,
                    IsUsed = false,
                    CreateTime = Clock.Now
                };
                config.StartIncreament++;
            }
            return result;
        }

        private static string GetRandomString(CodeGenConfig config, Random random)
        {
            if (config.IsOnlyNumberCode)
            {
                return GetRandomNumString(config, random);
            }
            else
            {
                return GetRandomString(config.Length);
            }
        }

        private static string GetRandomNumString(CodeGenConfig config, Random random)
        {
            int ran = random.Next(0, Convert.ToInt32(Math.Pow(10.0, config.Length) - 1));
            return Convert.ToString(ran, CultureInfo.InvariantCulture).PadLeft(config.Length, '0');
        }

        private static string GetRandomString(int length)
        {
            return RandomStringBuilder.Create(length);
        }
    }
}